package lol.clann.minecraft.springboot.bukkit.plugin;

import lol.clann.minecraft.springboot.bukkit.plugin.logger.LoggerFactory;
import lol.clann.minecraft.springboot.bukkit.utils.BukkitUtils;
import org.slf4j.Logger;
import org.slf4j.helpers.NOPLogger;
import org.springframework.boot.loader.JarLauncher;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 *
 * @author pyz
 * @date 2019/4/8 8:27 PM
 */
public class Adapter {
    private static Logger logger;
    private static final Method addURL;
    private static final ClassLoader classLoader = Adapter.class.getClassLoader();

    public static void setLoggerIfInvalid(Logger logger) {
        if (Adapter.logger == null || Adapter.logger instanceof NOPLogger) {
            Adapter.logger = logger;
        }
    }

    public static Logger getLogger() {
        return logger;
    }

    static {
        logger = LoggerFactory.getLogger("SpringBootPlugin");
        try {
            addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            addURL.setAccessible(true);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public static void start(File pluginDir) throws Exception {
//        初始化BukkitUtils
        BukkitUtils.getBukkitVersionNumber();
        getLogger().info("add spring boot starter to classPath");
//        启动starter
        JarLauncher.main(new String[0]);
    }

    private static void addStarterToClassPath(File pluginDir) throws NoSuchMethodException, MalformedURLException, InvocationTargetException, IllegalAccessException {
        File dir = pluginDir.toPath().resolve("SpringBootPlugin").toFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        for (File file : dir.listFiles()) {
            if (!file.getName().endsWith(".jar")) {
                continue;
            }
            addURL.invoke(classLoader, file.toURI().toURL());
        }
    }

    public static boolean suppourtJava8() {
        try {
            Java8Test.testJava8();
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

}
